<?php
namespace app\index\controller;

use app\index\model\LunwenTransactionRecordModel;
use app\index\model\ZhiniaoUserModel;
use app\index\service\LunwenTransactionRecordServer;
use app\index\service\TransactionService;
use app\lunwen\model\LunwenWordDocumentModel;
use kbitAdmin\tools\Data;
use think\admin\Controller;

/**
 * Class Index
 * @package app\index\controller
 */
class Index extends Controller
{
    public $zhiniao_user = null;
    public function __construct(\think\App $app)
    {
        parent::__construct($app);

        $zhiniao_user = session('zhiniao_user');
        $manage_list = [
        // [
            //     'name' => '主页',
            //     'url' => '/index/index/index'
            // ]
        ];
        $current_user = ZhiniaoUserModel::find($zhiniao_user['id']);
        if($zhiniao_user){
            $manage_list[] = [
                'name' => '写论文',
                'url' => '/index/index/addlunwen',
            ];
            $manage_list[] = [
                'name' => '论文管理',
                'url' => '/index/index/manage',
            ];
            $manage_list[] = [
                'name' => '费用中心',
                'url' => '/index/index/cost',
            ];
        }
        $this->assign([
            'manage_list' => $manage_list,
            'zhiniao_user' => $zhiniao_user,
            'current_user' => $current_user,
        ]);
    }

    private function checkUserLogin(){
        $zhiniao_user = session('zhiniao_user');
        $this->zhiniao_user = $zhiniao_user;
        if(!$zhiniao_user){
            $this->assign([
                'message' => '请先登录后，再尝试操作。',
                'url' => url('login'),
                'url_title' => '去登录',
            ]);
            $this->fetch('error');
        }
    }


    public function index()
    {
        $this->checkUserLogin();

        return $this->addlunwen();      

    }
    public function register()
    {
        return $this->fetch();
    }


    public function logout()
    {
        session('zhiniao_user', null);
        return $this->redirect('index');
    }

    public function addlunwen()
    {
        $this->checkUserLogin();
        $user = ZhiniaoUserModel::find($this->zhiniao_user['id']);
        $this->assign(['balance' => $user['balance']]);
        if($this->request->isGet()){

            return $this->fetch('addlunwen');
        }else{

            $title = $this->request->post('title');
            $cengci = $this->request->post('cengci');
            if(!$title){
                $this->assign([
                    'message' => '论文标题不能为空',
                    'url' => url('addlunwen'),
                    'url_title' => '返回',
                ]);
                $this->fetch('error');
                return false;
            }
            
            if(!isset(LunwenWordDocumentModel::CENGCI_TYPE_ARR[$cengci])){
                $this->assign([
                    'message' => '层次选择有误，必须选择本科或者专科',
                    'url' => url('addlunwen'),
                    'url_title' => '返回',
                ]);
                $this->fetch('error');
                return false;
            }

            // 判断用户余额是否大于层次论文所需余额。
            if($user['balance'] < LunwenWordDocumentModel::CENGCI_TYPE_ARR[$cengci]['cost']){
                $this->assign([
                    'message' => '当前知鸟券不足，请充值后再次尝试提交',
                    'url' => url('cost'),
                    'url_title' => '去充值',
                ]);
                $this->fetch('error');
                return false;
            }

            // 将添加任务的逻辑，与金额绑定在一起。事务统一处理
            $document = LunwenTransactionRecordServer::lunwenCreateAndDeduct($title, $user, LunwenWordDocumentModel::CENGCI_TYPE_ARR[$cengci]['cost']);
            
            
            if($document){
                $document_id = $document['document_id'];
                $this->assign([
                    'message' => '论文任务添加成功',
                    'url' => url('manage'),
                    'url_title' => '查看',
                ]);
                $queue_code = sysqueue(sprintf("[%s]生成论文-%s", $this->zhiniao_user['username'], $title), sprintf("y:OpenAiCreateLunwen --id=%s", $document_id), 0);
                // dump($queue);
                LunwenWordDocumentModel::where(['document_id' => $document_id])->update(['queue_code' => $queue_code]);
                $this->fetch('success');
            }else{
                $this->assign([
                    'message' => '论文任务添加失败，请联系管理员。',
                    'url' => url('addlunwen'),
                    'url_title' => '返回',
                ]);
                $this->fetch('error');
            }
        }
    }

    public function manage()
    {
        $this->checkUserLogin();
        $map = [];
        $map['uid'] = $this->zhiniao_user['id'];
        $lunwenDocument = new LunwenWordDocumentModel();
        $this->_page($lunwenDocument->with(['queue'])->where($map)->order('document_id desc'));
        return $this->fetch('manage');
    }


    public function cost()
    {
        $this->checkUserLogin();
        $map = [];
        $map['uid'] = $this->zhiniao_user['id'];
        $transactionRecordModel = new LunwenTransactionRecordModel();
        $this->_page($transactionRecordModel->where($map)->order('id desc'));
        return $this->fetch('cost');
    }

    // 处理注册请求
    public function doRegister()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');

        // 验证用户名是否已存在
        if (ZhiniaoUserModel::where('username', $username)->find()) {
            return json(['code' => 0, 'msg' => '用户名已存在']);
        }

        // 创建用户
        $user = new ZhiniaoUserModel;
        $user->username = $username;
        $user->password = password_hash($password, PASSWORD_DEFAULT);
        if (!$user->save()) {
            return json(['code' => 0, 'msg' => '注册失败']);
        }
        return json(['code' => 1, 'msg' => '注册成功']);
    }

    public function login()
    {
        if($this->request->isGet()){
            return $this->fetch('login');
        }
        $username = $this->request->post('username');
        $password = $this->request->post('password');

        $user = ZhiniaoUserModel::where('username', $username)->find();
        if (!$user || !password_verify($password, $user->password)) {
            $this->error('登录失败');
        } else {
            session('zhiniao_user', $user);
            $this->redirect('addlunwen');
        }
    }
}